package basic

import (
	"chat/app"
	"chat/app/common"
	"chat/app/dao"
	"chat/app/model"
	"chat/utils"
	"context"
	"fmt"
	"github.com/go-playground/validator/v10"
	"math/rand"
	"strconv"
	"strings"
)

// 注册args
type userRegister struct {
	Mobile   string `from:"mobile" validate:"required,min=11,max=20"`
	Passwd   string `from:"passwd" validate:"required,min=6,max=25"`
	Passwdr  string `from:"passwdr" validate:"required,min=6,max=25"`
	Avatar   string `from:"avatar"`
	Sex      string `from:"sex"`
	Nickname string `from:"nickname"`
	Memo     string `from:"memo"`
}

// RegisterAuthService 用户注册
func RegisterAuthService(ctx context.Context, c *app.Context) any {

	// 创建返回信息
	data := make(map[string]interface{})
	code := common.INVALID_PARAMS

	// 接收参数
	var mobile string
	var passwd string
	var passwdr string
	var avatar string
	var sex int8
	var nickname string
	var memo string
	if c.GetHeader("Content-Type") == "application/json" {
		// 接收 application/json 类型的参数
		var paramJson userRegister
		if err := c.ShouldBindJSON(&paramJson); err != nil {
			return common.Response(common.ERROR, err.Error(), data)
		}
		mobile = paramJson.Mobile
		passwd = paramJson.Passwd
		passwdr = paramJson.Passwdr
		avatar = paramJson.Avatar
		u32, _ := strconv.Atoi(paramJson.Sex)
		//u64, _ := strconv.ParseUint(strVar, 10, 32)
		sex = int8(u32)
		nickname = paramJson.Nickname
		memo = paramJson.Memo
	} else {
		// form 形式参数
		mobile = c.PostForm("mobile")
		passwd = c.PostForm("passwd")
		passwdr = c.PostForm("passwdr")
		avatar = c.PostForm("avatar")
		strVar := c.PostForm("sex")
		u32, _ := strconv.Atoi(strVar)
		//u64, _ := strconv.ParseUint(strVar, 10, 32)
		sex = int8(u32)
		nickname = c.PostForm("nickname")
		memo = c.PostForm("memo")
	}

	// 验证参数
	valid := validator.New()
	a := userRegister{
		Mobile:  mobile,
		Passwd:  passwd,
		Passwdr: passwdr,
	}
	ok := valid.Struct(a)
	if ok != nil {
		// 翻译成中文
		trans := utils.ValidateTransInit(valid)
		verrs := ok.(validator.ValidationErrors)
		errs := make(map[string]string)
		for key, value := range verrs.Translate(trans) {
			errs[key[strings.Index(key, ".")+1:]] = value
		}
		fmt.Println(errs)
		return common.Response(code, common.GetMsg(code), data)
	}

	if passwd != passwdr {
		return common.Response(common.ERROR_AUTH, common.GetMsg(common.ERROR_AUTH), data)
	}

	// 查询用户
	sql := "SELECT * FROM " + new(model.User).TableName() + " WHERE mobile = ? limit 1"
	info := dao.UserQueryRawDao(sql, mobile)
	if info != nil {
		return common.Response(common.ERROR, "账号已存在", data)
	}

	// 插入数据
	user := model.User{Mobile: mobile, Avatar: avatar, Sex: sex, Nickname: nickname, Memo: memo}
	user.Salt = fmt.Sprintf("%06d", rand.Int31n(10000))
	user.Token = ""
	user.Passwd = utils.MakePasswd(passwd, user.Salt)
	dao.UserCreate(&user)
	if user.Id == 0 {
		return common.Response(common.ERROR, "账号创建失败", data)
	}
	code = common.SUCCESS

	return common.Response(code, common.GetMsg(code), data)
}
